//package com.xuelang.component;
//
//
//import com.alibaba.fastjson2.JSON;
//import com.xuelang.pipeline.client.common.constant.Constant;
//import com.xuelang.pipeline.client.common.exception.AuthException;
//import com.xuelang.pipeline.client.common.exception.BizException;
//import com.xuelang.pipeline.client.common.result.ApiResult;
//import com.xuelang.pipeline.client.common.util.UserContext;
//import com.xuelang.pipeline.client.common.util.WebJwtUtil;
//import com.xuelang.pipeline.client.common.vo.UserVO;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.tomcat.util.codec.binary.Base64;
//import org.springframework.http.MediaType;
//import org.springframework.util.StringUtils;
//import org.springframework.web.util.ContentCachingRequestWrapper;
//
//import jakarta.servlet.*;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.io.PrintWriter;
//import java.nio.charset.StandardCharsets;
//import java.util.ArrayList;
//import java.util.Enumeration;
//import java.util.List;
//
//
///**
// * 授权访问过滤器
// *
// * @author xiwen.zxg
// * @since 2024/5/16
// */
//@Slf4j
//public class AuthorizationAccessFilter implements Filter {
//
//    private static List<String> IGNORE_URLS = new ArrayList<String>();
//    static {
//    }
//
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        //log.info("----------------------request parse start------------------------------------------------");
//        //log.info("requestUrl={}", request.getRequestURI());
//        //log.info("Protocol={}", request.getProtocol());
//
//        // 判断是否忽略请求头authorization
//        if (shouldIgnoreAuthorization(request.getRequestURI())) {
//            filterChain.doFilter(request, response);
//            return;
//        }
//
//        // 解析请求头authorization是否正确并有效
//        try {
//            String contentType = parseContentType(request);
//            //log.info("Parsed Header.Content-Type={}", contentType);
//            String authorization = parseAuthorization(request);
//            //log.info("Authorization={}", authorization);
//            String phone = WebJwtUtil.getPhone(authorization);
//            //log.info("Parsed Header.Phone={}", phone);
//            validateAuthorization(authorization);
//            //log.info("Parsed Header.Authorization={}", authorization);
//            //log.info("----------------------request parse end------------------------------------------------");
//
//            UserVO currentUser = UserVO.builder().phone(phone).code(phone).build();
//            UserContext.setCurrentUser(currentUser);
//            log.info(">>>currentUser={}", currentUser);
//            //recordRequestLog(request);
//            filterChain.doFilter(request, response);
//            //recordResponseLog(servletResponse);
//
//        } catch (AuthException e) {
//            log.warn("Exception>>>desc:{}", e.getMessage());
//            writeJsonToResponse(response, ApiResult.fail(e.getMessage()));
//        } catch (Exception e) {
//            log.error("Exception>>>desc:{}", e.getMessage());
//            writeJsonToResponse(response, ApiResult.fail(e.getMessage()));
//        }
//    }
//
//    /**
//     * 记录响应日志信息
//     *
//     * @param response
//     */
//    private void recordResponseLog(ServletResponse response) {
//        // 记录响应日志信息
//    }
//
//    /**
//     * 记录请求日志信息
//     *
//     * @param request
//     */
//    private void recordRequestLog(HttpServletRequest request) throws IOException {
//
//        ServletRequestWrapper servletRequestWrapper = new ServletRequestWrapper(request);
//        ContentCachingRequestWrapper contentCachingRequestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
//
//        String requestURI = request.getRequestURI();
//        Enumeration<String> headerNames = request.getHeaderNames();
//        String requestUrl = request.getRequestURL().toString();
//        String queryString = request.getQueryString();
//        String protocol = request.getProtocol();
//        String method = request.getMethod();
//        //String body = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
//        log.info("===========================my request begin================================================");
//        log.debug("URI         : {}", requestURI);
//        log.debug("URL         : {}", requestUrl);
//        log.debug("Method      : {}", method);
//        log.debug("Headers     : {}", headerNames);
//        log.debug("Protocol    : {}", protocol);
//        log.debug("Params      : {}", queryString);
//        log.debug("Request body: {}", new String(contentCachingRequestWrapper.getContentAsByteArray(), StandardCharsets.UTF_8));
//        log.info("==========================my request end================================================");
//    }
//
//    /**
//     * 向响应流中写JSON格式数据
//     *
//     * @param response
//     * @param object
//     * @throws IOException
//     */
//    private void writeJsonToResponse(HttpServletResponse response, Object object) throws IOException {
//        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
//        PrintWriter outWriter = response.getWriter();
//        outWriter.write(JSON.toJSONString(object));
//        outWriter.flush();
//        outWriter.close();
//    }
//
//    /**
//     *  是否应该忽略请求头authorization的解析和验证
//     *
//     * @param requestUrl
//     * @return
//     */
//    private boolean shouldIgnoreAuthorization(String requestUrl) {
//        return IGNORE_URLS.contains(requestUrl);
//    }
//
//    /**
//     * 解析请求头Content-Type
//     *
//     * @return
//     */
//    private String parseContentType(HttpServletRequest request) {
//        String contentType = request.getHeader(Constant.REQUEST_HEADER_PREFIX_ContentType);
//        if (StringUtils.isEmpty(contentType)) {
//            contentType = request.getHeader(Constant.REQUEST_HEADER_PREFIX_contenttype);
//        }
//        if (StringUtils.isEmpty(contentType)) {
//            throw new BizException("Header Content-Type Invalid.");
//        }
//        return contentType;
//    }
//    /**
//     * 解析请求头authorization
//     *
//     * @param request
//     * @return
//     */
//    private String parseAuthorization(HttpServletRequest request) {
//        String basicAuthorization = request.getHeader(Constant.REQUEST_HEADER_NAME_Authorization);
//        if (StringUtils.isEmpty(basicAuthorization)) {
//            basicAuthorization = request.getHeader(Constant.REQUEST_HEADER_NAME_authorization);
//        }
//        //log.info(".Authorization={}", basicAuthorization);
//        if (StringUtils.isEmpty(basicAuthorization)) {
//            throw new AuthException("Header Authorization Not Found.");
//        }
//        // 验证参数authorization所携带用户名和密码是否合法
//        String encodeAuthorization = basicAuthorization.replace(Constant.REQUEST_HEADER_PREFIX_Authorization, "").replace(" ", "");
//        //log.info(".encodeAuthorization={}", encodeAuthorization);
//        if (!StringUtils.isEmpty(encodeAuthorization)) {
//            encodeAuthorization = encodeAuthorization.replace("Bearer", "");
//        }
//        byte[] decode = Base64.decodeBase64(encodeAuthorization);
//        if (decode == null || decode.length == 0) {
//            throw new AuthException("Header Authorization Invalid.");
//        }
//        String decodeAuthorization = new String(decode, StandardCharsets.UTF_8);
//        //log.info(".decodeAuthorization={}", decodeAuthorization);
//
//        return decodeAuthorization;
//    }
//
//    /**
//     * 验证请求头authorization
//     *
//     * @param authorization
//     */
//    private void validateAuthorization(String authorization) {
//        // 待完善---这里应该多加一步判断Authorization有效性的验证
//        // 可以抛出authorization无效异常 throw new AuthException(ErrorCode.AUTHORIZATION_NOT_VALID);
//    }
//}
